﻿using AutoMapper;
using Microsoft.Extensions.Configuration;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using X23.Application.MenuManagement.Dto;
using X23.EFCore.Repository;
using X23.EFCore.Service;
using X23.Model.Menu;

namespace X23.Application.MenuManagement
{
    public class MenuManagementService : CRUDService<MenuDto, Menu>, IMenuManagementService
    {
        private readonly IRepository<Menu> _menuRepository;
        private readonly IMapper _mapper;

        public MenuManagementService(IRepository<Menu> menuRepository, IMapper mapper) : base(menuRepository, mapper)
        {
            _menuRepository = menuRepository;
            _mapper = mapper;
        }

        public async Task<List<MenuTreeDto>> GetMenuTree()
        {
            var list = (await _menuRepository.GetAllAsync()).ToList();
            var result = _mapper.Map<List<MenuTreeDto>>(list.Where(x => x.ParentId == 0).OrderBy(x => x.Seq).ToList());
            result.ForEach(item =>
            {
                var itemList = _mapper.Map<List<MenuTreeDto>>(list.Where(x => x.ParentId == item.Id).OrderBy(x => x.Seq).ToList());
                if (itemList.Count > 0)
                {
                    item.Children = itemList;
                }
                else
                {
                    item.Children = new List<MenuTreeDto>();
                }
            });
            return result;
        }
    }
}
